package rpc.config;

import lombok.extern.slf4j.Slf4j;
import rpc.remote.transport.netty.server.NettyRpcServer;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

/**
 * @ClassName: CustomShutDownHook
 * @Description: 一个钩子，当要关闭一个服务时，将其相应注册的服务也注销掉
 * @author: Kowk
 * @since:1.0.0
 */
@Slf4j
public class CustomShutDownHook {
    private static final CustomShutDownHook CUSTOM_SHUT_DOWN_HOOK = new CustomShutDownHook();

    public static CustomShutDownHook getCustomShutDownHook(){
        return CUSTOM_SHUT_DOWN_HOOK;
    }

    public void clearAll(){
        log.info("添加关机钩子用于关闭所有注册");
        //jvm中增加一个关闭的钩子，当jvm关闭的时候，会执行系统中已经设置的所有通过方法addShutdownHook添加的钩子，当系统执行完这些钩子后，jvm才会关闭。
        //所以这些钩子可以在jvm关闭的时候进行内存清理、对象销毁等操作。

        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            try {
                InetSocketAddress inetSocketAddress = new InetSocketAddress(InetAddress.getLocalHost().getHostAddress(), NettyRpcServer.PORT);
            } catch (UnknownHostException e) {
                log.error("在getHostAddress的时候发生异常");
            }
                })

        );
    }
}
